package com.bamboocloud.ws.demo.service;

import com.alibaba.fastjson.JSON;
import com.banboocloud.Codec.BamboocloudFacade;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class OrgUpdateService extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//AES
	//	private static final String key = "123456";
	//	private static final String type = "AES";
	//	private static final String signType = "MD5";

	//SM4
	private static final String key = "JLB6L6MJVIT5Z7IL";
	private static final String type = "SM4";
	private static final String signType = "SM3";

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String bodyparam = BamboocloudUtils.getRequestBody(request);
		System.out.println("first--param-->" + bodyparam);
		//报文解密
		bodyparam = BamboocloudUtils.getPlaintext(bodyparam, key, type);
//		System.out.println("xml--param-->" + bodyparam);
//		bodyparam = XmlUtils.xmlToJson(bodyparam);
		System.out.println("json--param-->" + bodyparam);
		Map<String,Object> reqmap = (Map<String,Object>) JSON.parse(bodyparam);
		//验证签名
		if (BamboocloudUtils.verify(reqmap, signType).booleanValue()) {
			String username = (String) reqmap.get("bimRemoteUser");
			String password = (String) reqmap.get("bimRemotePwd");

			BamboocloudUtils.checkUsernamePassword(username, password);

			String uid = updateOrg(bodyparam);
			Map<String,Object> schema = new HashMap<String,Object>();
			schema.put("bimRequestId", reqmap.get("bimRequestId"));
			schema.put("resultCode", "0");
			schema.put("message", "success");

			String mapJson = JSON.toJSONString(schema);
//			System.out.println("response---json-->" + mapJson);
//			mapJson = XmlUtils.jsonToXml(mapJson);
			System.out.println("response----->" + mapJson);
			mapJson = BamboocloudFacade.encrypt(mapJson, key, type);

			PrintWriter out = response.getWriter();
			out.write(mapJson);
			out.close();
		}
	}

	private String updateOrg(String bodyparam) {
		System.out.println("update org XXX" + bodyparam);
		return null;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}